package com.example.securitytest.service;

import com.example.securitytest.domain.LoginUser;
import com.example.securitytest.domain.ResponseResult;
import com.example.securitytest.domain.User;
import com.example.securitytest.util.JwtUtil;
import com.example.securitytest.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
// 写登录的核心代码
public class LoginServiceImpl implements LoginService {

    @Autowired
    // 先在SecurityConfig，使用@Bean注解重写官方的authenticationManagerBean类，然后这里才能注入成功
    private AuthenticationManager authenticationManager;

    @Autowired
    // RedisCache是我们在utils目录写好的类
    private RedisCache redisCache;

    @Override
    // ResponseResult和user是我们在domain目录写好的类
    public ResponseResult login(User user) {

        // 用户在登录页面输入的用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        // 获取AuthenticationManager的authenticate方法来进行用户认证
        Authentication authenticate = null;

        try {
            // 认证，并返回认证信息，会调用UserDetailsService中的方法
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 判断上面那行的authenticate是否为null，如果是则认证没通过，就抛出异常
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过，就使用userid生成一个jwt，然后把jwt存入ResponseResult后返回
        // 返回UserDetailsService的loadUserByUserName的返回对象。
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getXxuser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);

        // 把完整的用户信息存入redis，其中userid作为key，注意存入redis的时候加了前缀 login:
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        redisCache.setCacheObject("login:" + userid, loginUser);
        return new ResponseResult(200, "登录成功", map);
    }


    /**
     * SecurityContextHolder.getContext() 获取的是当前线程(请求)的上下文
     * @return
     */
    @Override
    public ResponseResult logout() {

        // 获取我们在JwtAuthenticationTokenFilter类写的SecurityContextHolder对象中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        // loginUser是我们在domain目录写好的实体类
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getXxuser().getId();
        System.out.println(userId);
        redisCache.deleteObject("login:" + userId);

        return new ResponseResult(200,"注销成功！");
    }
}